package com.university.mentalhealthplatform.global.rbac.model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

public class CustomUserDetails implements UserDetails {

    // 正确的日志记录器初始化方式
    private static final Logger logger = LoggerFactory.getLogger(CustomUserDetails.class);


    private final UUID id;
    private final String username;
    private final String password;
    private final Set<String> roles;       // 存储角色名称
    private final Set<String> permissions; // 存储权限名称
    private final Set<GrantedAuthority> authorities;
    //private final User user;

    // 构造函数
    public CustomUserDetails(User user) {
        //this.user = user;
        this.id = user.getId();
        this.username = user.getUsername();
        this.password = user.getPassword();

        // 提取角色名称
        this.roles = user.getRoles().stream()
                .map(Role::getIdentifier)
                .collect(Collectors.toSet());

        // 提取权限名称
        this.permissions = user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .map(Permission::getIdentifier)
                .collect(Collectors.toSet());

        // 将角色和权限转换为 GrantedAuthority 集合
        this.authorities = user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .map(permission -> new SimpleGrantedAuthority(permission.getIdentifier()))
                .collect(Collectors.toSet());

        // 将角色也添加为 GrantedAuthority
        this.authorities.addAll(
                this.roles.stream()
                        .map(role -> new SimpleGrantedAuthority(role))
                        .collect(Collectors.toSet())
        );

    }

    public UUID getId() {
        return id;
    }

    public Set<String> getRoles() {
        return roles;
    }

    public Set<String> getPermissions() {
        return permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    // 根据业务需求自定义
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }



}
